//log
eclipse.runtime.include("../log/log.eclipse.js");
log.log('include file');

/**
 * 文件读写对象
 * 
 * @param {String}
 *            filePath--文件路径（不传则表示当前活动文件）
 */
var File = function(filePath) {
	this.filePath = filePath;
};

/**
 * 读取文件内容
 * 
 * @return {String}--文件内容
 */
File.prototype.getContent = function() {
	var file, reader, line, sb, tempchars;
	if (!this.filePath) {
		log.log('get current editor file content');
		if (eclipse.editors.selection.text) {
			return eclipse.editors.selection.text;
		}
		return eclipse.editors.document.get();
	} else {
		file = new Packages.java.io.File(this.filePath || ""), sb = new Packages.java.lang.StringBuffer(), line = null;
		log.log('file.getContent and filePath=' + this.filePath);
		if (file.exists()) {
			br = new Packages.java.io.BufferedReader(new Packages.java.io.FileReader(file));
			while ((line = br.readLine()) != null) {
				// sb.append(line);
				sb.append(line).append('\r\n');
			}
			return sb.toString();
		}
		log.log('file.getContent and file not exists');
		/*
		 * file=new Packages.java.io.File(this.filePath||""),sb=new
		 * Packages.java.lang.StringBuffer(); log.log('file.getContent and
		 * filePath='+this.filePath); if(file.exists()){ reader = new
		 * Packages.java.io.InputStreamReader(new
		 * Packages.java.io.FileInputStream(file)); tempchars = new
		 * Packages.java.char[1024]; while (reader.read(tempchars) != -1) {
		 * sb.append(tempchars); } return sb.toString(); }
		 * log.log('file.getContent and file not exists');
		 */
	}
};

/**
 * 写入内容到文件
 * 
 * @param {String}
 *            content--内容
 */
File.prototype.write = function(content) {
	var file, bw;
	if (!this.filePath) {
		log.log('set content to current editor file and content is:');
		log.log('-----------------------华丽的分割线-----------------------');
		log.log(content);
		log.log('------------------------------------------------------');
		eclipse.editors.document.set(content);
	} else {
		file = new Packages.java.io.File(this.filePath || "");
		log.log('file.write and filePath=' + this.filePath);
		if (file.exists()) {
			bw = new Packages.java.io.BufferedWriter(new Packages.java.io.FileWriter(file));
			bw.write(content);
			bw.close();
		}
		log.log('file.write and file not exists');
	}
};
